/**
 * @file XListView.java
 * @package me.maxwin.view
 * @create Mar 18, 2012 6:28:41 PM
 * @author Maxwin
 * @description An ListView support (a) Pull down to refresh, (b) Pull up to load more.
 * Implement IXListViewListener, and see stopRefresh() / stopLoadMore().
 */
package com.wufun.overseas.view;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;

import com.wufun.overseas.R;
import com.wufun.overseas.utils.NetWorkUtils;
import com.wufun.overseas.view.ptr.PtrDefaultHandler;
import com.wufun.overseas.view.ptr.PtrFrameLayout;


import java.util.concurrent.atomic.AtomicBoolean;

public class XListView2 extends ListView implements OnScrollListener {
    public final static String TAG = "XListView";

    protected float mLastY = -1; // save event y
    protected float mLastX = -1; // save event y
    protected Scroller mScroller; // used for scroll back
    protected OnScrollListener mScrollListener; // user's scroll listener

    // the interface to trigger refresh and load more.

    protected IXListViewLoadMore        mLoadMore;
    protected IXListViewRefreshListener mOnRefresh;

    // -- header view
    protected XListViewHeader mHeaderView;
    // header view content, use it to calculate the Header's height. And hide it
    // when disable pull refresh.
    protected RelativeLayout mHeaderViewContent;
    protected TextView mHeaderTimeView;
    protected int             mHeaderViewHeight; // header view's height
    protected boolean       mEnablePullRefresh = true;
    protected AtomicBoolean mPullRefreshing    = new AtomicBoolean(false); // is refreashing.

    // -- footer view
    protected XListViewFooter mFooterView;
    protected boolean         mEnablePullLoad;
    protected boolean         mPullLoading;
    protected boolean mIsFooterReady = false;

    // total list items, used to detect is at the bottom of listview.
    protected int mTotalItemCount;

    // for mScroller, scroll back from header or footer.
    protected int mScrollBack;
    protected final static int SCROLLBACK_HEADER = 0;
    protected final static int SCROLLBACK_FOOTER = 1;

    protected final static int     SCROLL_DURATION        = 400; // scroll back duration
    protected final static int     PULL_LOAD_MORE_DELTA   = 50; // when pull up >= 50px at bottom,trigger load more.
    protected final static float   OFFSET_RADIO           = 2f; // support iOS like pull feature.
    //support perload
    private                int     preloadCount           = 0;
    private                boolean mEnablePullLoadDefault = false;


    //intercept
//    private ViewGroup mParentIntercepView;
//    private boolean disallowIntercept = false;

    /**
     * @param context
     */
    public XListView2(Context context) {
        super(context);
        initWithContext(context);
        setFriction(ViewConfiguration.getScrollFriction() * 10);
        setFastScrollEnabled(false);
    }

    public XListView2(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    public XListView2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    protected void initWithContext(Context context) {
        mScroller = new Scroller(context, new DecelerateInterpolator());
        // XListView need the scroll event, and it will dispatch the event to
        // user's listener (as a proxy).
        super.setOnScrollListener(this);

        // init header view
        mHeaderView = new XListViewHeader(context);
        mHeaderViewContent = (RelativeLayout) mHeaderView
                .findViewById(R.id.xlistview_header_content);
        mHeaderTimeView = (TextView) mHeaderView
                .findViewById(R.id.xlistview_header_time);
        //addHeaderView(mHeaderView);

        // init footer view
        mFooterView = new XListViewFooter(context);
//        mFooterView.setState(XListViewFooter.STATE_NORMAL);

        // init header height
       /* mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        mHeaderViewHeight = mHeaderViewContent.getHeight();
                        getViewTreeObserver()
                                .removeGlobalOnLayoutListener(this);
                    }
                });*/
        // 补充修改
        disablePullLoad();
        disablePullRefreash();
        addFooterView(mFooterView);

    }


    //    @Override
//    protected void onLayout(boolean changed, int l, int t, int r, int b) {
//        try {
//            super.onLayout(changed, l, t, r, b);
//            // make sure XListViewFooter is the last footer view, and only add once.
//            if (mIsFooterReady == false) {
//                // if not inflate screen ,footerview not add
//                if (getAdapter() != null) {
//                    if (getLastVisiblePosition() != (getAdapter().getCount() - 1)) {
//                        mIsFooterReady = true;
//                        addFooterView(mFooterView);
//                    }
//                }
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
    DataSetObserver mDataObserver;

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        mDataObserver = new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                preload();
            }
        };
        adapter.registerDataSetObserver(mDataObserver);
    }

    public void setPreLoadCount(int count) {
        this.preloadCount = count;
    }


    /**
     * enable or disable pull down refresh feature.
     *
     * @param enable
     */

    private PtrDefaultHandler ptrDefaultHandler = new PtrDefaultHandler() {
        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
//            LogUtil_.logVerbos("onRefreshBegin----------");
            startOnRefresh();
            if (mRefreshListener != null) {
                mRefreshListener.onRefresh();
            }
        }

        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
        }

    };
    private IXListViewRefreshListener mRefreshListener;

    public void setPullRefreshEnable(IXListViewRefreshListener refreshListener) {
        mRefreshListener = refreshListener;
        if (getParent() != null && getParent() instanceof PtrFrameLayout) {
            ((PtrFrameLayout) getParent()).setPtrHandler(ptrDefaultHandler);
            ((PtrFrameLayout) getParent()).disableWhenHorizontalMove(true);
        }

       /* mEnablePullRefresh = true;
        mHeaderViewContent.setVisibility(View.VISIBLE);
        this.mOnRefresh = refreshListener;*/

    }

    public void disablePullRefreash() {
        mEnablePullRefresh = false;
        // disable, hide the content
        mHeaderViewContent.setVisibility(View.INVISIBLE);
    }

    /**
     * enable or disable pull up load more feature.
     *
     * @param
     */
    public void setPullLoadEnable(IXListViewLoadMore loadMoreListener) {
        mEnablePullLoad = true;
        mEnablePullLoadDefault = true;
        this.mLoadMore = loadMoreListener;
        mPullLoading = false;
        mFooterView.show();
        mFooterView.setState(XListViewFooter.STATE_NORMAL);
        // both "pull up" and "click" will invoke load more.
        mFooterView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//				startLoadMore();
                mPullLoading = true;
                mFooterView.setState(XListViewFooter.STATE_LOADING);
                if (mLoadMore != null) {
                    mLoadMore.onLoadMore();
                }
            }
        });

    }

    public void disablePullLoad() {
        mEnablePullLoad = false;
        mFooterView.hide();
        mFooterView.setOnClickListener(null);
    }

    public void hidePullLoad() {
        mEnablePullLoad = false;
        mFooterView.hide();
    }

    public void showPullLoad() {
        mEnablePullLoad = true;
        mFooterView.show();
    }

    /**
     * stop refresh, reset header view.
     */
    public void stopRefresh() {
       /* if (mPullRefreshing.get()) {
            Log.d(TAG, "method stopRefresh() called.");
            mPullRefreshing.set(false);
            resetHeaderHeight();
        }*/
        if (getParent() != null && getParent() instanceof PtrFrameLayout) {
            ((PtrFrameLayout) getParent()).refreshComplete();
        }

    }

    /**
     * stop load more, reset footer view.
     */
    public void stopLoadMore() {
//        Logger.log(TAG, "stopLoadMore");

        if (mPullLoading && mEnablePullLoad) {
//            Logger.log(TAG, "stopLoadMore-called");
//            Log.d(TAG, "method stopLoadMore() called.");
            mPullLoading = false;
            mFooterView.setState(XListViewFooter.STATE_NORMAL);
        }
        Log.i("Two", "stopLoadMore");
    }

    public void reset() {
        mEnablePullLoad = true;
        mEnablePullRefresh = true;
        mFooterView.setState(XListViewFooter.STATE_NORMAL);

    }

    protected void invokeOnScrolling() {
        if (mScrollListener instanceof IXScrollListener) {
            IXScrollListener l = (IXScrollListener) mScrollListener;
            l.onXScrolling(this);
        }
    }

    protected void updateHeaderHeight(float delta) {
        mHeaderView.setVisibleHeight((int) delta
                + mHeaderView.getVisibleHeight());
        if (mEnablePullRefresh && !mPullRefreshing.get()) { // 未处于刷新状态，更新箭头
            if (mHeaderView.getVisibleHeight() > mHeaderViewHeight) {
                mHeaderView.setState(XListViewHeader.STATE_READY);
            } else {
                mHeaderView.setState(XListViewHeader.STATE_NORMAL);
            }
        }
        setSelection(0); // scroll to top each time
    }

    /**
     * reset header view's height.
     */
    protected void resetHeaderHeight() {
        int height = mHeaderView.getVisibleHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn't shown fully. do nothing.
        if (mPullRefreshing.get() && height <= mHeaderViewHeight) {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing.get() && height > mHeaderViewHeight) {
            finalHeight = mHeaderViewHeight;
        }
        Log.d("xlistview", "resetHeaderHeight-->" + (finalHeight - height));
        mScrollBack = SCROLLBACK_HEADER;
        mScroller.startScroll(0, height, 0, finalHeight - height,
                SCROLL_DURATION);

        // trigger computeScroll
        invalidate();
    }

    protected void resetHeaderHeight(int disy) {
        int height = mHeaderView.getVisibleHeight();
        if (height == 0) // not visible.
            return;
        // refreshing and header isn't shown fully. do nothing.
        if (mPullRefreshing.get() && height <= mHeaderViewHeight) {
            return;
        }
        int finalHeight = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mPullRefreshing.get() && height > mHeaderViewHeight) {
            finalHeight = mHeaderViewHeight;
        }
        mScrollBack = SCROLLBACK_HEADER;
        Log.d("xlistview", "resetHeaderHeight-->" + (finalHeight - height));
        mScroller.startScroll(0, height, 0, finalHeight - height + 100,
                SCROLL_DURATION);
        // trigger computeScroll
        invalidate();
    }

    protected void updateFooterHeight(float delta) {
        int height = mFooterView.getBottomMargin() + (int) delta;
        if (mEnablePullLoad && !mPullLoading) {
            if (height > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
                // more.
                mFooterView.setState(XListViewFooter.STATE_READY);
            } else {
                mFooterView.setState(XListViewFooter.STATE_NORMAL);
            }
        }
        mFooterView.setBottomMargin(height);

        // setSelection(mTotalItemCount - 1); // scroll to bottom
    }

    protected void resetFooterHeight() {
        int bottomMargin = mFooterView.getBottomMargin();
        if (bottomMargin > 0) {
            mScrollBack = SCROLLBACK_FOOTER;
            mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
                    SCROLL_DURATION);
            invalidate();
        }
    }

    protected void startLoadMore() {
        if (mEnablePullLoad
                && mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA
                && !mPullLoading) {
            Log.d(TAG, "method startLoadMore() called.");
            mPullLoading = true;
            mFooterView.setState(XListViewFooter.STATE_LOADING);
            if (mLoadMore != null) {
                mLoadMore.onLoadMore();
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        if (mLastY == -1) {
            mLastY = ev.getRawY();
        }

        if (mLastX == -1) {
            mLastX = ev.getRawX();
        }

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = ev.getRawY();
                mLastX = ev.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                final float deltaY = ev.getRawY() - mLastY;
                mLastY = ev.getRawY();
                Log.v("xlistview", "onTouchEvent " + " LastVisiblePosition " + getLastVisiblePosition() + " mTotalItemCount " + mTotalItemCount + ";mPullLoading=" + mPullLoading + ";mEnablePullLoad=" + mEnablePullLoad);

              /*  if (getFirstVisiblePosition() == 0
                        && (mHeaderView.getVisibleHeight() > 0 || deltaY > 0)
                        && !mPullRefreshing.get()) {
                    // the first item is showing, header has shown or pull down.

                    *//*if (mEnablePullRefresh && !mPullRefreshing.get()) {
                        updateHeaderHeight(deltaY / OFFSET_RADIO);
                        invokeOnScrolling();
                    }*//*

                } else*/
                if (getLastVisiblePosition() == mTotalItemCount - 1
                        && (mFooterView.getBottomMargin() > 0 || deltaY < 0)
                        && !mPullLoading) {
                    // last item, already pulled up or want to pull up.
                    if (mEnablePullLoad) {
                        updateFooterHeight(-deltaY / OFFSET_RADIO);
                    }
                } else if (preloadCount != 0) {
                    preload();

                }

                break;
            default:
                mLastY = -1; // reset
               /* if (getFirstVisiblePosition() == 0) {
//                    if (!mPullRefreshing.get()&&mEnablePullRefresh&&mHeaderView.getVisibleHeight() > mHeaderViewHeight) {
                    if (!mPullRefreshing.get() && mEnablePullRefresh) {
                        // invoke refresh
                      *//*  startOnRefresh();
                        resetHeaderHeight();*//*
                    }

                } else */

                if (getLastVisiblePosition() == mTotalItemCount - 1) {
                    // invoke load more.
                    startLoadMore();
                    resetFooterHeight();
                }
                break;
        }

        return super.onTouchEvent(ev);
    }

    public synchronized void preload() {

//        Logger.log(TAG, "preload"
//                , "mPullRefreshing=" + mPullRefreshing, "mEnablePullLoad=" + mEnablePullLoad, "mPullLoading=" + mPullLoading
//                , "count-load=" + (getLastVisiblePosition() >= mTotalItemCount - preloadCount));

        if (NetWorkUtils.isNetworkConnected(getContext()) && !mPullRefreshing.get() && mEnablePullLoad && !mPullLoading && getLastVisiblePosition() >= mTotalItemCount - preloadCount) {
//            Logger.log(TAG,"do-preload");

            mPullLoading = true;
            mFooterView.setState(XListViewFooter.STATE_LOADING);
            if (mLoadMore != null) {
                mLoadMore.onLoadMore();
            }
        }
    }

    /**
     * xiet 20151012
     */
    public void showHeaderLoading() {
       /* Log.d(TAG, "method showHeaderLoading() called.");
        mPullRefreshing.set(true);
        mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
        updateHeaderHeight(mHeaderViewHeight);
        resetHeaderHeight();*/
        if (getParent() != null && getParent() instanceof PtrFrameLayout) {
            ((PtrFrameLayout) getParent()).autoRefresh();
        }
    }

    protected void startOnRefresh() {
        // mHeaderView.getVisibleHeight() > mHeaderViewHeight

        if (mEnablePullLoadDefault) {
            mEnablePullLoad = true;
            mFooterView.show();
            mFooterView.setState(XListViewFooter.STATE_NORMAL);
        }

       /* if(getParent()!= null && getParent() instanceof PtrFrameLayout){

        *//*&& mHeaderView.getVisibleHeight() > mHeaderViewHeight && !mPullRefreshing.get()*//*

           *//* mPullRefreshing.set(true);
            mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
            if (mOnRefresh != null) {
                Log.d(TAG, "method startOnRefresh() called.");
                mOnRefresh.onRefresh();
            }*//*
                //如果默认设置的是可加载更多，当刷新的时候恢复默认设置 2115.11.14 by psk
                if (mEnablePullLoadDefault) {
                    mEnablePullLoad = true;
                    mFooterView.show();
                    mFooterView.setState(XListViewFooter.STATE_NORMAL);
                }

        }*/


    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            if (mScrollBack == SCROLLBACK_HEADER) {
// mHeaderView.setVisibleHeight(mScroller.getCurrY());
            } else {
                mFooterView.setBottomMargin(mScroller.getCurrY());
            }
            postInvalidate();
            invokeOnScrolling();
        }
        super.computeScroll();
    }

    @Override
    public void setOnScrollListener(OnScrollListener l) {
        mScrollListener = l;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        int first = view.getFirstVisiblePosition();
        int count = view.getChildCount();
//        Logger.log(TAG, "onScrollStateChanged", "scrollState=" + scrollState
//                , "first=" + first, "count=" + count, "mTotalItemCount=" + mTotalItemCount
//                , "canPreload=" + (first + count > mTotalItemCount));

        if (scrollState == SCROLL_STATE_IDLE || (first + count > mTotalItemCount)) {//冗余判断listview是否到了最末端
//            Logger.log(TAG, "onScrollStateChanged", "preload");
            preload();
        }

        if (mScrollListener != null) {
            mScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        // send to user's listener
//        Log.v(TAG, "onScroll  " + firstVisibleItem + " visibleItemCount " + visibleItemCount + " totalItemCount " + totalItemCount + ";mPullRefreshing=" + mPullRefreshing.get() + ";mPullLoading=" + mPullLoading);
        mTotalItemCount = totalItemCount;
//        if (preloadCount != 0) {
//            if (!mPullRefreshing.get() && mEnablePullLoad && !mPullLoading && getLastVisiblePosition() >= mTotalItemCount - preloadCount) {
//                mPullLoading = true;
//                mFooterView.setState(XListViewFooter.STATE_LOADING);
//                if (mLoadMore != null) {
//                    Log.v(TAG,"mLoadMore.onLoadMore() called.");
//                    mLoadMore.onLoadMore();
//                }
//            }
//        }
        if (mScrollListener != null) {
            mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
                    totalItemCount);
        }
    }

    public void setNoMore() {
//        Logger.log(TAG,"setNoMore");

        stopLoadMore();
        mFooterView.show();
        mFooterView.setState(XListViewFooter.STATE_REFRE_NOMORE);
        mEnablePullLoad = false;
        mFooterView.setOnClickListener(null);
    }

    public boolean isRefreshing() {
        return mPullRefreshing.get();
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    @Override
    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
        if (mOnOverScrolled != null) {
            mOnOverScrolled.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
        }
    }

    OnOverScrolled mOnOverScrolled;

    public void setOnOverScrolled(OnOverScrolled l) {
        this.mOnOverScrolled = l;
    }

    public interface OnOverScrolled {
        void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY);
    }

    @Override
    protected int computeVerticalScrollExtent() {
        return super.computeVerticalScrollExtent();
    }

    @Override
    protected int computeVerticalScrollOffset() {
        return super.computeVerticalScrollOffset();
    }
}
